package com.vdian.udc.apiadmin.common.ds;

import com.vdian.udc.apiadmin.common.logger.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Title:数据源路由器
 * @Description:TODO
 * @author:xu.he
 * @create:2016/12/15 上午10:45
 * @version:v1.0
 */
public class UdcApiAdminDataSourceRouter extends AbstractRoutingDataSource {

    private Logger logger= LoggerFactory.getLogger(UdcApiAdminDataSourceDynamicAop.class);

    public UdcApiAdminDataSourceRouter(DataSource masterDataSource, DataSource slaveDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(UdcApiAdminDataSourceType.WRITE.name(), masterDataSource);
        targetDataSources.put(UdcApiAdminDataSourceType.READ.name(), slaveDataSource);
        this.setDefaultTargetDataSource(masterDataSource);
        this.setTargetDataSources(targetDataSources);
    }

    @Override
    protected Object determineCurrentLookupKey() {
        String typeKey = UdcApiAdminDataSourceContextHolder.getJdbcType();
        if(UdcApiAdminDataSourceType.WRITE.name().equals(typeKey)){
            logger.info("{DataSourceRouter set write key !!!!}");
            return UdcApiAdminDataSourceType.WRITE.name();
        }
        return UdcApiAdminDataSourceType.READ.name();
    }
}
